How to Add a "Dark Mode" Toggle in Any Website (CSS & JS Guide)
Modern websites require a Dark Mode to improve accessibility and user experience. In this guide, I will show you the exact code to add a toggle switch
Modern websites require a Dark Mode to improve accessibility and user experience. In this guide, I will show you the exact code to add a toggle switch to your Blogger site.
1. The CSS Variables
We use CSS variables to manage colors. Add this to your theme's CSS:
:root {
--bg-color: #ffffff;
--text-color: #333333;
}
[data-theme="dark"] {
--bg-color: #121212;
--text-color: #e0e0e0;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
transition: background-color 0.3s;
}
2. The JavaScript Switch
This script checks the user's system preference and saves their choice in LocalStorage.
const toggleTheme = () => {
const current = document.documentElement.getAttribute('data-theme');
const target = current === 'dark' ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', target);
localStorage.setItem('theme', target);
};
Conclusion: Simple CSS variables make theming easy. Stay tuned to EarnEmpier Pro for more developer tutorials.
Join the conversation